package data

import (
	"context"
	"digitalhuman/internal/conf"
	"fmt"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/redis/go-redis/v9"
	"go.uber.org/zap"
	"time"
)

func NewRds(conf *conf.Data) *redis.Client {
	c := redis.NewClient(&redis.Options{
		Addr:     conf.Redis.Addr,
		Password: conf.Redis.Password, // 没有密码，默认值
		DB:       0,                   // 默认DB 0
	})

	// sentinel地址 有redis集群的时候可以切换一下
	//var addr = []string{conf.Redis.SentinelAddr0, conf.Redis.SentinelAddr1, conf.Redis.SentinelAddr2}
	//c := rds.NewSentinelClient(conf.Redis.MasterName, conf.Redis.SentinelPassword, conf.Redis.Password, addr, int(conf.Redis.Db))
	pingRes, err := c.Ping(context.TODO()).Result()
	if err != nil {
		log.Error("redis ping failed", err)
		panic(err)
	}
	log.Info("redis ping", zap.String("result", pingRes))
	return c
}

type RdbData struct {
	rdb *redis.Client
}

func (r *RdbData) LockStoryboard(storyId int) {
	ctx := context.Background()
	ok, err := r.rdb.SetNX(ctx, fmt.Sprintf("story_id_%d", storyId), "lock_value", 10*time.Second).Result()
	if err != nil || !ok {
		fmt.Println("Failed to acquire lock")
		return
	}
}

func (r *RdbData) UnLockStoryboard(storyId int) {
	// Unlock
	_, err := r.rdb.Del(context.Background(), "lock_key").Result()
	if err != nil {
		fmt.Println("Failed to release lock")
	}
}
